<?php
namespace App\Workers;

use App\Services\SchoolMajorScoreService;
use App\Helpers\LoggerHelper;
use App\Services\SchoolScoreSpiderService;
use Monolog\Logger;
use Workerman\Connection\TcpConnection;
use Workerman\Worker;

class SchoolMajorScoreWorker
{

    /**
     * @var SchoolMajorScoreService
     */
    protected $service;

    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var array 命令行参数
     */
    protected $options = [
        'limit' => 0,
        'proxy_enable' => true,
    ];

    /**
     * 构造函数
     *
     * @param int $limit 命令行参数
     */
    public function __construct(int $limit)
    {
        $this->options = array_merge($this->options, ['limit' => $limit]);
        $this->service = new SchoolMajorScoreService($this->options['proxy_enable']);
    }


    /**
     * 静态运行方法
     *
     * @param Worker $worker
     * @param int $limit
     */
    public static function run(Worker $worker, int $limit = 0): void
    {
        $instance = new self($limit);
        $instance->logger = new Logger('SchoolMajorScoreWorker');
        $worker->onWorkerStart = [$instance, 'onWorkerStart'];
        $worker->onMessage = [$instance, 'onMessage'];
    }

    /**
     * Worker启动回调
     *
     * @param Worker $worker
     */
    public function onWorkerStart(Worker $worker): void
    {
        $startTime = microtime(true);
        $stats = $this->service->processSchoolMajorScore($this->options['limit']);

        $this->printStats($stats, $startTime);
        $worker->stop();
    }

    /**
     * 打印统计信息
     *
     * @param array $stats
     * @param float $startTime
     */
    protected function printStats(array $stats, float $startTime): void
    {
        $elapsed = round(microtime(true) - $startTime, 2);
        $successRate = $stats['total'] > 0
            ? round($stats['success'] / $stats['total'] * 100, 2)
            : 0;

        $this->logger->info("\n院校专业分数线采集完成");
        $this->logger->info("==============================");
        $this->logger->info("总采集院校数: {$stats['total']}");
        $this->logger->info("成功数: {$stats['success']}");
        $this->logger->info("失败数: {$stats['failed']}");
        $this->logger->info("成功率: {$successRate}%");
        $this->logger->info("耗时: {$elapsed}秒");
        $this->logger->info("==============================");
    }

    /**
     * 解析命令行选项
     *
     * @param array $argv
     */
    protected function parseOptions(array $argv)
    {
        foreach ($argv as $arg) {
            if (str_starts_with($arg, '--')) {
                $parts = explode('=', substr($arg, 2));
                $name = $parts[0];
                $value = $parts[1] ?? true;

                if (isset($this->options[$name])) {
                    $this->options[$name] = is_numeric($value) ? (int)$value : $value;
                }
            }
        }
    }

    /**
     * 处理HTTP请求
     *
     * @param TcpConnection $connection
     * @param mixed $data
     */
    public function onMessage(TcpConnection $connection, $data)
    {
        $connection->send(json_encode(['code' => 200, 'message' => 'OK']));
    }


    public static function run_bak(Worker $worker, int $limit = 0)
    {
        $worker->onWorkerStart = function() use ($limit) {
            $logger = LoggerHelper::channel('school-major-score-worker', 'school-major-score-worker.log');
            
            try {
                $service = new SchoolMajorScoreService();
                $colleges = $service->getActiveColleges();
                
                $total = count($colleges);
                $logger->info("开始采集院校专业分数数据，共{$total}所院校");
                
                $processed = 0;
                foreach ($colleges as $college) {
                    if ($limit > 0 && $processed >= $limit) {
                        break;
                    }
                    
                    try {
                        $service->crawlCollegeMajorScores($college->school_id);
                        $logger->info("成功采集院校ID:{$college->school_id}的专业分数数据");
                        $processed++;
                        
                        // 添加随机请求间隔(1-3秒)防止IP被封
                        $delay = mt_rand(1, 3);
                        sleep($delay);
                    } catch (\Exception $e) {
                        $logger->error("采集院校ID:{$college->school_id}失败: " . $e->getMessage());
                        continue;
                    }
                }
                
                $logger->info("院校专业分数采集完成，共处理{$processed}/{$total}所院校");
            } catch (\Exception $e) {
                $logger->error("院校专业分数采集Worker异常: " . $e->getMessage());
            }
        };
    }
}
